# coding:utf8

from appserver import db_store
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
import hashlib
"""
设备表
"""


class RemoteHost(db_store.Model):
    __tablename__ = "remote_hosts"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    username = db_store.Column(db_store.String(255), nullable=False, comment=u"用户名")
    password = db_store.Column(db_store.String(255), nullable=False, comment=u"密码")
    ip_addr = db_store.Column(db_store.String(128), nullable=False, comment=u"ip地址")
    port = db_store.Column(db_store.Integer, nullable=False, comment=u"服务器端口号")
    description=db_store.Column(db_store.String(255),comment=u"服务器描述")
    # 说明结束
    status = db_store.Column(db_store.Integer, comment=u"状态", default=0)  # 0-正常 1-禁用 2-弃用

    def __repr__(self):
        return "<RemoteHost %s>" % self.name

    def get_max_id(self):
        val = db_store.session.query(func.max(RemoteHost.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):
        try:
            if self.id is None:
                self.id = self.get_max_id() + 1
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            db_store.session.rollback()
            print(e)
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False
    
    def get_dic(self):
        rdic={}
        rdic["id"]=self.id
        rdic["username"]=self.username
        rdic["password"]=self.password
        rdic["ip_addr"]=self.ip_addr
        rdic["port"]=self.port
        rdic["description"]=self.description
        rdic["status"]=self.status
        return rdic

    @staticmethod
    def get_remote_host_by_id(id):
        return RemoteHost.query.filter_by(id=id).first()

    @staticmethod
    def get_remote_host_by_ip(ip_addr):
        return RemoteHost.query.filter_by(ip_addr=ip_addr).first()

    @staticmethod
    def get_remote_host_all():
        return RemoteHost.query.all()